﻿using System;
using System.IO;
using System.Web.Hosting;

//自定义命名空间
using DreamCube.Framework.Utilities.Log;
using DreamCube.Foundation.Basic.Extensions.System;
using DreamCube.Foundation.Basic.Extensions.System.StringIO;

namespace DreamCube.Apps.WinForm.Common.DotNetWebServer
{
    /// <summary>
    /// AspNetHost的管理类
    /// </summary>
    public static class AspNetHostManager
    {

        /// <summary>
        /// 创建程序域
        /// </summary>
        public static AspNetHost CreateAspNetHost(String virtualPath, String physicalPath)
        {
            try
            {
                AspNetHostManager.CopyDependFileToTargetWeb(physicalPath);
                AspNetHost host = (AspNetHost)ApplicationHost.CreateApplicationHost(typeof(AspNetHost),
                                virtualPath, physicalPath);
                return host;
            }
            catch (Exception ex)
            {
                LoggerManager.Logger.MakeLogAsync(ex);
            }
            return null;
        }

        /// <summary>
        /// 创建程序域并启动开始处理请求
        /// </summary>
        public static AspNetHost CreateAspNetHostAndStartProcessRequest(String[] prefix, String virtualPath,
                                                                String physicalPath, String[] defaultDocs, String[] restrictedPaths = null)
        {
            try
            {
                AspNetHost host = AspNetHostManager.CreateAspNetHost(virtualPath, physicalPath);
                if (host != null)
                    host.StartProcessRequest(prefix, virtualPath, physicalPath, defaultDocs, restrictedPaths);

                return host;
            }
            catch (Exception ex)
            {
                LoggerManager.Logger.MakeLogAsync(ex);
            }
            return null;
        }

        #region "私有方法"

        /// <summary>
        /// 把服务器运行所依赖的dllcopy到网站的bin目录下
        /// </summary>
        private static void CopyDependFileToTargetWeb(String targetPath)
        {
            String directoryName = Path.Combine(targetPath, "bin");
            //确保bin目录存在
            directoryName.EnsurePath();

            try
            {
                String[] files = null;
                Environment.CurrentDirectory.GetFiles(out files, "*.dll");

                if (files != null)
                    for (Int32 i = 0; i < files.Length; i++)
                        File.Copy(files[i], files[i].Replace(files[i].LeftOfLast("\\"), directoryName), true);
            }
            catch (IOException ex)
            {
                LoggerManager.Logger.MakeLogAsync(ex);
            }
        }

        #endregion

    }
}
